import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { reorderTodos } from '../redux/actions';
import TodoItem from './TodoItem';

const TodoList = () => {
  const todos = useSelector(state => state.todos);
  const dispatch = useDispatch();
  const [draggedItem, setDraggedItem] = useState(null);

  const handleDragStart = (e, index) => {
    setDraggedItem(index);
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', e.target.parentNode);
  };

  const handleDragOver = (e, index) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e, index) => {
    e.preventDefault();
    if (draggedItem !== null) {
      const newTodos = [...todos];
      const [removed] = newTodos.splice(draggedItem, 1);
      newTodos.splice(index, 0, removed);
      dispatch(reorderTodos(newTodos));
      setDraggedItem(null);
    }
  };

  return (
    <div>
      {todos.map((todo, index) => (
        <TodoItem
          key={todo.id}
          todo={todo}
          index={index}
          dragStart={handleDragStart}
          dragOver={handleDragOver}
          drop={handleDrop}
        />
      ))}
    </div>
  );
};

export default TodoList;